package com.webvihar.access2db.asynctasks;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.webvihar.access2db.R;
import com.webvihar.access2db.restapi.A2DbWebResult;
import com.webvihar.access2db.restapi.AbstractA2DbWebRequest;
import com.webvihar.access2db.utils.NetworkConnection;

/**
 * @author Viswanath Kumar Sandu
 * 
 */
public class A2DbAsyncWebRequestTask extends AbstractAsyncTask {

	private ProgressDialog _progressDialog;
	private Handler _handle;
	
	public A2DbAsyncWebRequestTask(boolean shouldToastWhenNoNetworkIsPresent, Context context, Handler handle, ProgressDialog progressDialog) {
		super(context, shouldToastWhenNoNetworkIsPresent);
		_handle = handle;
		_progressDialog = progressDialog;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if (context != null && !NetworkConnection.isConnected(context) && shouldToastWhenNoNetworkIsPresent) {
			Toast.makeText(context, context.getText(R.string.no_internet_connection), Toast.LENGTH_SHORT).show();
		}
		if (!isConnected) {
			cancel(true);
		}
		else if (_progressDialog != null) _progressDialog.show();		
	}  

	@Override
	protected A2DbWebResult<?> doInBackground(AbstractA2DbWebRequest... params) {
		super.doInBackground(params);	
		if (params == null || params[0] == null) return null;
		return params[0].requestDelegate.execute(params[0]);
	}

	@Override
	protected void onPostExecute(A2DbWebResult<?> result) {
		super.onPostExecute(result);
		sendMessage(result);
		if (_progressDialog != null) _progressDialog.cancel();
	}

	private void sendMessage(A2DbWebResult<?> result) {
		if (_handle == null) return;
		Message m = Message.obtain();
		m.obj = result;
		_handle.sendMessage(m);
	}
}
